<?php
/**
 * Created by PhpStorm.
 * User: gesangdianzi
 * Date: 2019/11/24
 * Time: 17:11
 */

namespace app\controllers;


use app\models\Discuss;
use app\traits\Response;
use yii\data\Pagination;
use yii\web\Controller;

class ApiController extends Controller
{
    use Response;

    public $key = '4562211554784';
    public $secret_code = '66562158884116651';

    public $enableCsrfValidation = false;

    public function beforeAction($action)
    {
        $key = \Yii::$app->request->post("key");
        $secret_code = \Yii::$app->request->post("secret_code");
        if($key!= $this->key || $secret_code != $this->secret_code){
            return $this->ajaxError("验证失败");
        }

        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }

    public function actionAdd(){
        $content = \Yii::$app->request->post("content");
        if(empty($content)){
            return $this->ajaxError("请填写寄语内容");
        }
        $model = new Discuss();
        $model->content = $content;
        $model->create_time = date("Y-m-d H:i:s");
        return $model->save() ? $this->ajaxSuccess("添加成功"): $this->ajaxError("添加失败");
    }

    public function actionUpdate(){
        $id = \Yii::$app->request->post("id");
        $content = \Yii::$app->request->post("content");
        if(empty($content)){
            return $this->ajaxError("请填写寄语内容");
        }
        $model = Discuss::find()->where(['id'=>$id])->one();
        if(empty($model)){
            return $this->ajaxError("记录不存在");
        }
        $model->content = $content;
        return $model->save() ? $this->ajaxSuccess("添加成功"): $this->ajaxError("添加失败");
    }

    public function actionList(){
        $page = \Yii::$app->request->post("page" , 0);
        $size = \Yii::$app->request->post("size" , 20);
        if(empty($page)){
            $page = 0;
        }

        $query = Discuss::find();

        $page_query = clone $query;

        $pager = new Pagination(['totalCount' => $page_query->count()]);
        $pager->setPage($page);
        $pager->setPageSize($size);

        $list = Discuss::find()->limit($pager->limit)->offset($pager->offset)->orderBy("id desc")->asArray()->all();
        if(empty($list)){
            return $this->ajaxError("记录不存在");
        }
        return $this->ajaxSuccess($list);
    }

    public function actionDel(){
        $id = \Yii::$app->request->post("id");
        $model = Discuss::find()->where(['id'=>$id])->one();
        if(empty($model)){
            return $this->ajaxError("记录不存在");
        }
        return $model->delete() ? $this->ajaxSuccess("删除成功"): $this->ajaxError("删除失败");
    }
}